<template>
  <div class="container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <el-icon :size="30" @click="goBack()" style="color: black; margin: 8px">
        <ArrowLeftBold />
      </el-icon>
      <h2 class="title">下载安装</h2>
    </div>

    <!-- 标签切换 -->
    <div :class="['tab-item', { active: activeTab === 'records' }]">安装记录</div>

    <!-- 内容区域 -->
    <div class="content">
      <div v-if="loading" class="loading">
        <i class="el-icon-loading"></i>
        加载中...
      </div>

      <div v-else-if="installedApps.length === 0" class="empty">
        <i class="el-icon-folder-opened"></i>
        <p>空空如也~</p>
      </div>

      <div v-else class="app-list">
        <div v-for="app in installedApps" :key="app.downloadId" class="app-item">
          <div class="app-info">
            <div class="app-icon">
              <img
                v-if="app.iconUrl"
                :src="app.iconUrl"
                alt="应用图标"
                class="app-image"
                @error="handleImageError(app)"
              />
              <i v-else class="el-icon-mobile-phone"></i>
            </div>
            <div class="app-details">
              <h3>{{ app.name }}</h3>
            </div>
          </div>
          <button class="delete-button" @click="confirmDelete(app.userId, app.appId)">
            <i class="el-icon-delete"></i>
            删除
          </button>
        </div>
      </div>
    </div>
  </div>

  <HomeBottemIcons />
</template>

<script setup lang="ts">
import HomeBottemIcons from "@/components/HomeBottemIcons.vue";

import { ref, onMounted, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();
const global = getCurrentInstance().appContext.config.globalProperties;

const props = defineProps<{
  userId: string; // user的id
}>();

// 标签切换
const activeTab = ref("installed");

// 应用数据
const installedApps = ref<any[]>([]);
const loading = ref(false);

const fetchInstalledApps = async (userId: string) => {
  try {
    loading.value = true;

    // 先取用户已安装的应用
    const response_1 = await global.$http.get("/AppStore/download", {
      params: { userId },
    });
    console.log(response_1);

    installedApps.value = response_1.data;

    const download = "download";

    // 每个应用获取详细信息
    for (const app of installedApps.value) {
      try {
        const response_2 = await global.$http.get("/AppStore/app", {
          params: {
            download,
            id: app.appId,
          },
        });

        app.name = response_2.data.name;
        app.iconUrl = response_2.data.url;
      } catch (error) {
        console.error(`获取应用${app.appId}详情失败:`, error);
        // 设置默认值以防请求失败
        app.name = `未知应用 (ID: ${app.appId})`;
        app.iconUrl = "default-app-icon.png";
      }
    }
  } catch (error) {
    ElMessage.error("获取应用列表失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 删除应用
const deleteApp = async (userId: string, appId: string) => {
  const uninstall = "delete";

  try {
    // 预留接口请求
    await global.$http.get("/AppStore/download", {
      params: {
        delete: uninstall,
        userId: userId,
        appId: appId,
      },
    });

    ElMessage.success("删除成功");
    fetchInstalledApps(props.userId); // 重新加载列表
  } catch (error) {
    ElMessage.error("删除失败");
    console.error(error);
  }
};

// 确认删除
const confirmDelete = (userId: string, appId: string) => {
  ElMessageBox.confirm("确定要删除此应用吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteApp(userId, appId);
    })
    .catch(() => {
      // 取消操作
    });
};

const handleImageError = (app: any) => {
  // 图片加载失败时，移除url显示默认图标
  app.iconUrl = "";
  // 或者可以设置一个默认图片
  // app.iconUrl = '/default-app-icon.png';
};

const goBack = () => {
  router.go(-1);
}

// 初始化加载
onMounted(() => {
  fetchInstalledApps(props.userId);
});
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  padding: 15px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.title {
  margin-left: 15px;
  font-size: 20px;
  color: #333;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #e0e0e0;
  margin-bottom: 20px;
}

.tab-item {
  padding: 10px 20px;
  cursor: pointer;
  color: #666;
}

.tab-item.active {
  color: #409eff;
  border-bottom: 2px solid #409eff;
}

.content {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px;
  color: #999;
}

.empty {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 60px 0;
  color: #999;
}

.empty i {
  font-size: 50px;
  margin-bottom: 15px;
}

.app-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.app-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  transition: all 0.3s;
}

.app-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.app-info {
  display: flex;
  align-items: center;
}

.app-icon {
  width: 40px;
  height: 40px;
  background-color: #409eff;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  margin-right: 15px;
}

.app-details h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.app-details p {
  margin: 5px 0 0;
  font-size: 12px;
  color: #999;
}

.delete-button {
  background-color: #ff4d4f;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: background-color 0.3s;
}

.delete-button:hover {
  background-color: #ff7875;
}

.app-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.app-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}
</style>
